package com.briup.cart.service.impl;

import com.briup.cart.config.CartProperties;
import com.briup.cart.domain.vo.ShopCarGetListVO;
import com.briup.cart.mapper.ShopcarMapper;
import com.briup.cart.service.ShopcarService;
import com.briup.common.exception.SystemException;
import com.briup.common.response.CodeAndMessageEnum;
import com.briup.common.utils.UserContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
* @author qinyc
* @description 针对表【es_shopcar(购物车表)】的数据库操作Service实现
* @createDate 2024-12-24 09:16:52
*/
@Slf4j
@Service
public class ShopcarServiceImpl implements ShopcarService {

    @Autowired
    private ShopcarMapper shopcarMapper;

    //商品微服务中内容
//    @Autowired
//    private GoodsMapper goodsMapper;

    @Autowired
    private CartProperties cartProperties;

    @Override
    public Integer getCount(Integer userId) {
        Integer count = shopcarMapper.count(userId);
        return count;
    }

    @Override
    public void addShopCar(Integer goodsId, Integer num) {
        //1.获取登录用户
        Integer userId = 1/*TODO UserContext.getUser()*/;

        //2.判断商品是否已经存在
        List<ShopCarGetListVO> shopCarList =
                shopcarMapper.getListByUserId(userId);
        if(shopCarList != null && shopCarList.size() > 0) {
            for (ShopCarGetListVO shopCarGetListVO : shopCarList) {
                //2.1 商品已经存在，更新其数量
                if (shopCarGetListVO.getGoodsId().equals(goodsId)) {
                    int total = shopCarGetListVO.getNum() + num;
                    shopcarMapper.updateNum(shopCarGetListVO.getId(), total);

                    return;
                }
            }
        }

        //2.2 商品不存在，先判断购物车数量 是否 已经超过最大值
        checkCartsFull(userId);

        // 2.3 商品不存在，添加到购物车
        shopcarMapper.insert(1/*TODO UserContext.getUser()*/, goodsId, num);
    }

    //判断购物车是否已满
    private void checkCartsFull(Integer userId) {
        //获取指定用户购物车商品种类 数量
        long count = shopcarMapper.count(userId);
        log.info("购物车商品种类数量：" + count);
        //获取购物车商品种类最大数量
        int maxNum = cartProperties.getMaxItems();
        log.info("maxNum: " + maxNum);
        if (count >= maxNum) {
            throw new SystemException("购物车数量已满，超过" + maxNum, CodeAndMessageEnum.SHOP_CAR_IS_FULL);
        }
    }

    @Override
    public List<ShopCarGetListVO> getList() {
        //1.查询指定用户购物车中信息
        List<ShopCarGetListVO> shopcars =
                shopcarMapper.getListByUserId(1/*TODO UserContext.getUser()*/);
        log.info("补全商品信息前，shopcars: " + shopcars);

/*
        //2.获取购物车中所有商品的id
        List<Integer> goodIds = shopcars.stream().map(ShopCarGetListVO::getGoodsId)
                                                .collect(Collectors.toList());
        //3.根据ids查询商品信息
        List<Goods> goods = goodsMapper.queryGoodByIds(goodIds);
        if(CollectionUtils.isEmpty(goods)) {
            return shopcars;
        }

        //4.补全购物车中商品的相关信息(图片、价格、名称)
        Map<Integer, Goods> goodsMap =
                goods.stream().collect(Collectors.toMap(Goods::getId, Function.identity()));
        shopcars.forEach(shopCarGetListVO -> {
            Goods g = goodsMap.get(shopCarGetListVO.getGoodsId()); // 通过 goodsId 快速查找 Goods 对象
            if (g != null) {
                shopCarGetListVO.setCover(g.getCover());
                //商品在购物车中的数量
                shopCarGetListVO.setNum(shopCarGetListVO.getNum());
                //System.out.println("g.getStoreNum(): " + g.getStoreNum());
                shopCarGetListVO.setPrice(g.getPrice());
                shopCarGetListVO.setName(g.getName());
            }
        });
*/
        log.info("补全商品信息后，shopcars: " + shopcars);

        return shopcars;
    }

    @Override
    public void updateNum(Integer id, Integer num) {
        /**
         * 参数校验
         */
        if (Objects.isNull(id)){
            throw new SystemException(CodeAndMessageEnum.SHOP_CAR_ID_IS_NULL);
        }
        if (num < 1){
            throw new SystemException(CodeAndMessageEnum.SHOP_CAR_NUM_IS_ERROR);
        }

        shopcarMapper.updateNum(id,num);
    }

    @Override
    public void batchDelete(List<Integer> ids) {
        /**
         * 参数校验
         */
        //根据ID查询购物车信息是否存在
        List<Integer> existIds = shopcarMapper.selectById(ids);

        //获取不存在的ID
        ids.removeAll(existIds);

        if (!ids.isEmpty()){
            throw new SystemException(CodeAndMessageEnum.SHOP_CAR_IDS_IS_ERROR);
        }

        shopcarMapper.delete(existIds);
    }
}




